<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="time"></div>
    <div id="time2"></div>
    <script>
      // 获取当前时间
      const now = new Date();
      console.log("当前时间", now);
      // 获取指定时间
      const time = new Date("2024-01-01 12:00:00");
      console.log("指定时间", time);

      // 获取年份
      const year = now.getFullYear();
      console.log("年份", year);
      // 获取月份，月份要加1
      const month = now.getMonth();
      console.log("月份", month + 1);
      // 获取日期天数
      const day = now.getDate();
      console.log("日期天数", day);
      // 获取星期几，星期天是0
      const week = now.getDay();
      console.log("星期几", week);
      // 获取当前时间的小时
      const hour = now.getHours();
      console.log("当前时间的小时", hour);
      // 获取当前时间的分钟
      const minute = now.getMinutes();
      console.log("当前时间的分钟", minute);
      // 获取当前时间的秒
      const second = now.getSeconds();
      console.log("当前时间的秒", second);

      // 将当前时间以 YYYY-MM-DD HH:MM:SS 格式显示
      function formatTime(time) {
        const year = time.getFullYear();
        const month = time.getMonth() + 1;
        const day = time.getDate();
        const hour = time.getHours() < 10 ? "0" + time.getHours() : time.getHours();
        const minute = time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
        const second = time.getSeconds() < 10 ? "0" + time.getSeconds() : time.getSeconds();
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
      }
      document.getElementById("time").innerHTML = formatTime(now);

      // 第二种写法
      const time2 = new Date();
      document.getElementById("time2").innerHTML = time2.toLocaleString();


      // 时间戳
      // 1.getTime()
      console.log('时间戳1：',now.getTime());
      // 2.Date.now():只能获得当前的时间戳
      const timestamp = Date.now();
      console.log("时间戳2：", timestamp);
      // 3.+new Date()
      const timestamp2 = +new Date();
      console.log("时间戳3：", timestamp2);

      // 时间戳转换为日期
      const date = new Date(timestamp);
      console.log("时间戳转换为日期", date);

    </script>
  </body>
</html>
